
__license__ = """Copyright (c) 2009, Supreet Sethi, All rights reserved.
This following source code is licensed under the GPL v3 License."""

from urllib2 import urlopen, Request
from urllib import urlencode
from BeautifulSoup import BeautifulSoup
from simplejson import dumps
USER_AGENT = 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)'


class Result:
    def __init__(self, id):
        header = { 'User-Agent' : USER_AGENT, 'Referer':self.REF }
        data = urlencode({'regno': str(id), 'B1':'Submit'}) 
        req = Request(self.CBSE_URL,  data, header) 
        self.content = urlopen(req).read()
        self.process()

    def process(self):
        self.parser = BeautifulSoup(self.content)
        tables = self.parser.findAll('table', attrs={'width':'75%', 
                                                           'align':'center'})
        
        person_tables = tables[1]
        self.pdetails = []
        for item in person_tables.findAll('tr'):
           pair = item.findAll(text= lambda(text): len(text) > 2)
           self.pdetails.append((pair))
        marks_tables = self.parser.findAll('div', attrs={'align':'center'})[1]
        self.marks = []
        for tr in marks_tables.findAll('tr'):
            data = tr.findAll(text= lambda(text): len(text) > 2)
            clean_data = []
            for i in data:
                i = i.strip('&nbsp;')
                clean_data.append(i)
            self.marks.append((clean_data))

    def jsonexport(self):
        lst = [self.pdetails, self.marks]
        return dumps(lst)

        

class Result10(Result):
    CBSE_URL = "http://cbseresults.nic.in/class10/cbse10.asp"
    REF = "http://cbseresults.nic.in/class10/cbse10.htm"
    def __init__(self, id):
        Result.__init__(self, id)
    


class Result12(Result):
    CBSE_URL = "http://cbseresults.nic.in/class12/cbse12.asp"
    REF = "http://cbseresults.nic.in/class12/cbse12.htm"
    def __init__(self, id):
        Result.__init__(self, id)
    



